<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link rel="stylesheet" href="../css/mui.min.css" />
		<link rel="stylesheet" href="../css/sub-message.css" />
		<style type="text/css">
			.mui-table-view:after {
				height: 0;
			}
			
			.mui-bar-nav {
				-webkit-box-shadow: 0 0 0 #ccc;
				box-shadow: 0 0 0 #ccc;
			}
		</style>
	</head>

	<body>
		<div id="refreshContainer">
			<header class="mui-bar mui-bar-nav">
				<h1 class="mui-title">消 息</h1>
			</header>
			<div class="mui-content" id="subMessageList">
				<!--<div class="mui-table-view">
				<li class="mui-table-view-cell" style="text-align: center; color: #aaa; padding-top: 20px;">
					模块建设中......
				</li>
			</div>-->
				<!--任务通知模块-->
				<!--<ul class="mui-table-view">
					<li class="mui-table-view-cell mui-media">
						<div class="mui-slider-handle" data-status='2'>
							<div class="mui-col-xs-8 mui-pull-left">
								<img class="mui-media-object mui-pull-left" src="../images/task-tips.png">
								<div class="mui-media-body">
									消息通知
									<p class="mui-ellipsis">任务消息</p>
								</div>
							</div>
							<div class="mui-col-xs-4 mui-pull-right" style="display: inline-block; text-align: center; top: 0px;">
								<p class="mui-ellipsis">07:58:18</p>
								<span class="mui-badge mui-badge-danger" id="unreadCount">5</span>
							</div>
						</div>
					</li>
				</ul>-->
				<!--最近回话模块-->
				<ul class="mui-table-view" id="mui-content_chat" v-if="items.length !=0" v-for="item in items">
					<li class="mui-table-view-cell" :data-chattype="item.type" :data-id="item.id">
						<!--取消左滑删除操作，功能未完善-->
						<div class="mui-slider-right mui-disabled">
							<a class="mui-btn mui-btn-red">删除</a>
						</div>
						<!--单聊模块-->
						<div class="mui-slider-handle" v-if="item.type == 'singleChat'" data-status='0' :data-chattype="item.type" :data-name="item.name" :data-id="item.id" :data-userid="item.id" :data-groupid="item.sendee">
							<div class="mui-col-xs-8 mui-pull-left">
								<!--<img class="mui-media-object mui-pull-left" style="display: block; line-height: 42px;max-width: 42px;height: 42px;" v-bind:src="item.path">-->
								<img class="mui-media-object mui-pull-left" style="display: block; line-height: 42px;max-width: 42px;height: 42px;" src="../images/qq.png">
								<div class="mui-media-body" v-if="item.type == 'singleChat'">
									{{item.name}}
									<p v-if="item.msgtype == 'text' " class="mui-ellipsis">{{item.content}}</p>
									<p v-else class="mui-ellipsis">[图片]</p>
								</div>
							</div>
							<div v-show="item.nums !=0" class="mui-col-xs-4 mui-pull-right" style="display: inline-block; text-align: center; ">
								<p class="mui-ellipsis">{{item.time}}</p>
								<span class="mui-badge mui-badge-danger">{{item.nums}}</span>
							</div>
						</div>
						<!--群聊模板-->
						<div class="mui-slider-handle" v-else data-status='1' :data-msgid="item.msgid" :data-chattype="item.type" :data-title="item.title" :data-userid="item.id" :data-groupid="item.id" :data-id="item.id" :data-groupchatid="item.id">
							<div class="mui-col-xs-8 mui-pull-left" style="float:left;">
								<img class="mui-media-object mui-pull-left" style="display: block; line-height: 42px;max-width: 42px;height: 42px;" v-bind:src="item.path">
								<div class="mui-media-body">
									{{item.title}}
									<p v-if="item.msgtype == 'image' " class="mui-ellipsis">{{item.name}}:[图片]</p>
									<p v-else class="mui-ellipsis">{{item.name}}:{{item.content}}</p>
								</div>
							</div>
							<div v-show="item.nums !=0" class="mui-col-xs-4 mui-pull-right" style="float:right; display: inline-block; text-align: center; ">
								<p class="mui-ellipsis">{{item.time}}</p>
								<span class="mui-badge mui-badge-danger">{{item.nums}}</span>
							</div>
						</div>
					</li>
				</ul>
				<ul class="mui-table-view" id="mui-content_chat" v-show="items.length ==0">
					<li class="mui-table-view-cell" style="text-align: center; color: #aaa; padding-top: 20px;">
						暂无数据......
					</li>
				</ul>
			</div>
		</div>
	</body>

</html>
<script type="text/javascript" src="../js/mui.min.js"></script>
<script type="text/javascript" src="../js/jquery-2.1.0.js"></script>
<script type="text/javascript" src="../js/config.js"></script>
<script type="text/javascript" src="../js/common.js"></script>
<script type="text/javascript" src="../js/localStorage.js"></script>
<script type="text/javascript" src="../js/vue.min.js"></script>
<script type="text/javascript">
	var submessvm;
	var stroagekey; //最近会话id;
	var userinfo; //单聊用户信息

	var maillistInfo = localStorageFunc.get('organize'); //通讯录信息
	var loginid = localStorageFunc.get('token').userId;
	stroagekey = 'recentdialog_' + loginid;

	mui.init({
		pullRefresh: {
			container: "#refreshContainer", //下拉刷新容器标识，querySelector能定位的css选择器均可，比如：id、.class等
			down: {
				style: 'circle', //必选，下拉刷新样式，目前支持原生5+ ‘circle’ 样式
				color: '#2BD009', //可选，默认“#2BD009” 下拉刷新控件颜色
				height: '50px', //可选,默认50px.下拉刷新控件的高度,
				range: '100px', //可选 默认100px,控件可下拉拖拽的范围
				offset: '0px', //可选 默认0px,下拉刷新控件的起始位置
				auto: false, //可选,默认false.首次加载自动上拉刷新一次
				callback: pullrefresh //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
			}
		}
	});

	mui.plusReady(function() {

		//	 获取本地最近会话并存储到本地
		getLocalRecentChats();

		//	监听聊天消息时触发
		window.addEventListener('newChatMsg', function(e) {
			console.log('主动监听推送消息:' + JSON.stringify(e.detail));
			var msgCt = e.detail.data.content;
			var msgId = e.detail.data.sender;
			var chatId = e.detail.data.sendee;
			var chatType = e.detail.type;
			var msgType = e.detail.data.type;
			var read = e.detail.read;
			var msgTit;

			var itemsObj = {};
			if(e.detail) {
				switch(chatType) {
					case 'singleChat': //接收单聊处理
						if(maillistInfo) {
							$.each(maillistInfo.users, function(index, users) {
								if(msgId == users.id) {
									itemsObj = {
										name: users.name,
										//path: result.data[0].userList.avatar,
										type: 'singleChat',
										msgtype: msgType,
										id: msgId,
										content: msgCt,
										time: e.detail.data.sendTime,
										read: read,
										msgid: e.detail.data.id
									}
									pushMsg(itemsObj);
								}
							});
						}
						break;
					case 'groupChat': //	接收群聊处理

						ctdj.group.getGroup(function(r) {
							if(r.success) {
								if(r.result.length > 0) {
									$.each(r.result, function(index, item) {
										if(item.id == chatId) {
											msgTit = item.name;
										}
									});

									$.each(maillistInfo.users, function(index, users) {
										if(msgId == users.id) {
											itemsObj = {
												name: users.name,
												title: msgTit,
												path: '../images/group.png', //群头像默认
												type: 'groupChat',
												id: chatId,
												content: msgCt,
												msgtype: msgType,
												time: e.detail.data.sendTime,
												read: read,
												msgid: e.detail.data.id
											}
											pushMsg(itemsObj);
										}
									});

								}
							}

						});
						break;
					default:
						break;
				}

			}
		});

		//	推送到本人最近会话信息
		window.addEventListener('newChatRectentMsg', function(e) {
			var receivemsg = e.detail;
			console.log('主动推送推送到最近会话列表:' + JSON.stringify(receivemsg));
			console.log('本地:' + JSON.stringify(submessvm.items));
			if(receivemsg) {
				switch(receivemsg.type) {
					case 'singleChat': //接收单聊处理
						var flag = true;
						if(submessvm.items.length == 0) { //判断最近会话列表是否存在submessvm对象
							loadRectmsgSelf(0, receivemsg);
							flag = false;

						} else {
							$.each(submessvm.items, function(index, item) {
								if(item.id == receivemsg.data.sendee) {
									submessvm.items[index].msgtype = receivemsg.data.type; //更改消息类型
									submessvm.items[index].content = receivemsg.data.content;
									flag = false;
									return;
								}
							});
						}

						localStorageFunc.set(stroagekey, submessvm.items);
						//console.log('receivemsg=' + JSON.stringify(submessvm.items));
						if(flag) { //最近会话列表无匹配的单聊消息对话
							loadRectmsgSelf(1, receivemsg);
						}
						break;
					case 'groupChat': //接收群聊处理
						var flag = true;
						if(submessvm.items.length == 0) { //判断最近会话列表是否存在submessvm对象
							loadRectmsgSelf(0, receivemsg);
							flag = false;
						} else {
							$.each(submessvm.items, function(index, item) {
								if(item.id == receivemsg.data.sendee) {
									submessvm.items[index].msgtype = receivemsg.data.type; //更改消息类型
									submessvm.items[index].name = receivemsg.name;
									submessvm.items[index].content = receivemsg.data.content;
									submessvm.items[index].msgid = receivemsg.data.msgid;
									//console.log('群聊消息:' + JSON.stringify(submessvm.items));
									flag = false;
									return;
								}
							});
						}
						localStorageFunc.set(stroagekey, submessvm.items);
						if(flag) { //最近会话列表无匹配的群聊消息对话
							loadRectmsgSelf(1, receivemsg);
						}
						break;
					default:
						break;
				}
			};
		});

		//	处理未在群聊中时删除本地对应群聊会话信息	
		window.addEventListener('delChatRectentMsg', function(e) {
			console.log('删除=' + JSON.stringify(e.detail));
			console.log('items:' + JSON.stringify(submessvm.items));

			var indexnum;
			if(submessvm.items.length > 0) {
				$.each(submessvm.items, function(index, item) {
					if(item.msgid == e.detail) { //	找到对应的消息id并删掉
						indexnum = index;
						return;
					}
				});

				if(!indexnum) {
					submessvm.items.splice(indexnum, 1);
					localStorageFunc.set(stroagekey, submessvm.items);
				}
			}

		});

		//	监听退群时删除本地对应群聊会话信息	
		window.addEventListener('delExitRectentMsg', function(e) {
			var indexnum;
			if(submessvm.items.length > 0) {
				$.each(submessvm.items, function(index, item) {
					if(item.id == e.detail) { //	找到对应的消息id并删掉
						indexnum = index;
						return;
					}
				});

				if(!indexnum) {
					submessvm.items.splice(indexnum, 1);
					localStorageFunc.set(stroagekey, submessvm.items);
				}
			}

			mui.openWindow({
				url: '/html/organize-groups.html',
				id: 'organize-groups',
				createNew: false,
				show: {
					autoShow: true,
					aniShow: 'slide-in-right',
					duration: 300
				},
				waiting: {
					autoShow: false,
					title: '正在加载...'
				}
			})
		});

		//	监听更新群名称时修改本地对应群聊会话信息	
		window.addEventListener('updateNameRectentMsg', function(e) {
			if(submessvm.items.length > 0) {
				$.each(submessvm.items, function(index, item) {
					if(item.id == e.detail.groupsid) { //	找到对应的消息id并删掉
						submessvm.items[index].title = e.detail.groupsname;
						localStorageFunc.set(stroagekey, submessvm.items);
					}
				});
			}
		});

	});

	//	获取当前对话数据
	function getLocalRecentChats() {
		var sessions = localStorageFunc.get(stroagekey);
		console.log('sessions:' + JSON.stringify(sessions));
		if(sessions && sessions.length > 0) {
			initDom(sessions);
		} else {
			initDom([]);
		}
	}

	//	初始化DOM
	function initDom(result) {
		submessvm = new Vue({
			el: '#subMessageList',
			data: {
				items: result
			}
		})
		localStorageFunc.set(stroagekey, submessvm.items);
	};

	//	判断是否为数组对象
	function isArray(o) {
		return Object.prototype.toString.call(o) == '[object Array]';
	}

	//删除最近会话记录单条 
	$(document).on('slideleft', '#subMessageList .mui-table-view-cell', function(event) {
		var chatid = this.getAttribute('data-id');
		var elem = this;
		var btnArray = ['确认', '取消'];
		mui.confirm('确认删除该条会话？', '温馨提示', btnArray, function(e) {
			if(e.index == 0) {

				mui.swipeoutClose(elem); // 还原删除按钮状态

				setTimeout(function() {
					var indexnum = '';
					//console.log('本地对话条数:' + submessvm.items.length);
					//console.log('本地对话json:' + JSON.stringify(submessvm.items));
					if(submessvm.items.length > 0) {
						$.each(submessvm.items, function(index, item) {
							if(item.id == chatid) { //	找到对应的消息id并删掉
								/*console.log('当前显示索引:' + index);
								console.log('当前item:' + JSON.stringify(item));*/
								indexnum = index;
								return;
							}
						});

						submessvm.items.splice(indexnum, 1); // 删除当前id
						//console.log('执行删除后本地对话json:' + JSON.stringify(submessvm.items));
						localStorageFunc.set(stroagekey, submessvm.items);

					}
				}, 300)

			} else {
				setTimeout(function() {
					mui.swipeoutClose(elem);
				}, 0);
			}
		});
	});

	//	push数据
	function pushMsg(msg) {
		if(!submessvm.items) { //首次加载
			var arr = new Array();
			if(!isArray(msg)) {
				if(msg.read == 0) {
					msg.nums = 1;
				}
				arr.push(msg);
			} else {
				arr = msg;
			}
			submessvm.items = arr;
			localStorageFunc.set(stroagekey, submessvm.items);
			return;
		}
		getSession(msg);
	}

	function getSession(msg) {
		console.log('再次渲染：' + JSON.stringify(msg))
		var flag = true;
		if(submessvm.items.length > 0) {
			$.each(submessvm.items, function(index, item) {
				//	用户id、聊天类型  存在则替换
				if(msg.type == 'singleChat' && item.id == msg.id && item.type == msg.type) { //单聊
					if(msg.read == 0) {
						msg.nums = submessvm.items[index].nums + 1; //消息累加
					} else { //设置0条消息
						msg.nums = 0;
					}
					submessvm.items.splice(index, 1, msg);
					flag = false;
					localStorageFunc.set(stroagekey, submessvm.items);
					return;
				}

				if(msg.type == 'groupChat' && item.type == msg.type && item.id == msg.id) { //群聊、群聊id
					if(msg.read == 0) {
						msg.nums = Number(submessvm.items[index].nums) + 1; //消息累加
					} else {
						msg.nums = 0;
					}

					submessvm.items.splice(index, 1, msg);
					localStorageFunc.set(stroagekey, submessvm.items);
					flag = false;
					return;
				}

			});
		}

		if(flag) { //不存在则置顶添加
			if(msg.read == -1) {
				msg.nums = 0;
			} else if(msg.read == 0) {
				msg.nums = 1;
			}
			submessvm.items.splice(0, 0, msg);
			localStorageFunc.set(stroagekey, submessvm.items);
		}
	}

	//	单聊、群聊会话推送到最近会话
	function loadRectmsgSelf(type, selfMsg) {
		var singleObj = {}; //单聊临时存储对象
		var groupObj = {}; //群聊临时存储对象

		if(selfMsg.type == 'singleChat') {
			if(maillistInfo) {
				$.each(maillistInfo.users, function(index, users) {
					if(selfMsg.data.sendee == users.id) {
						singleObj = {
							name: users.name,
							path: '../images/qq.png',
							type: 'singleChat',
							msgtype: selfMsg.data.type,
							id: selfMsg.data.sendee,
							content: selfMsg.data.content,
							read: selfMsg.data.read
						}
					}
				});
			}
			getRenderRecent(type, singleObj);
		} else {
			var msgCt = selfMsg.data.content;
			var msgId = selfMsg.data.sender;
			var chatId = selfMsg.data.sendee;
			var chatType = selfMsg.type;
			var msgType = selfMsg.data.type;
			var read = -1; // 代表推送给本机最近会话列表
			var msgTit;

			ctdj.group.getGroup(function(r) {
				if(r.success) {
					if(r.result.length > 0) {
						$.each(r.result, function(index, item) {
							if(item.id == chatId) {
								msgTit = item.name;
							}
						});

						$.each(maillistInfo.users, function(index, users) {
							if(msgId == users.id) {
								itemsObj = {
									name: users.name,
									title: msgTit,
									path: '../images/group.png', //群头像默认
									type: 'groupChat',
									id: chatId,
									content: msgCt,
									msgtype: msgType,
									time: '',
									read: read
								}
								pushMsg(itemsObj);
							}
						});

					}
				}

			});

		}
	};

	//	渲染最近会话到消息列表
	function getRenderRecent(type, singleObj) {
		if(type == 0) {
			var arr = new Array();
			if(!isArray(singleObj)) {
				singleObj.nums = 0;
				arr.push(singleObj);
			} else {
				arr = singleObj;
			}
			submessvm.items = arr;
			localStorageFunc.set(stroagekey, submessvm.items);
			return;
		} else {
			singleObj.nums = 0;
			submessvm.items.splice(0, 0, singleObj);
			localStorageFunc.set(stroagekey, submessvm.items);
		}
	}

	//查看任务、最近回话详情
	mui('body').on('tap', '#mui-content_chat li .mui-slider-handle', function() {
		var status = this.getAttribute('data-status');
		var type = this.getAttribute('data-chattype');
		var chattype = this.getAttribute('data-chattype') == 'singleChat' ? '0' : '1'; //聊天类型
		var grounpid = chattype == '0' ? this.getAttribute('data-userid') : this.getAttribute('data-groupid');
		var cname = this.getAttribute('data-name');
		var ctitle = this.getAttribute('data-title');

		if(status == '0') {
			if(submessvm.items.length > 0) { //标记消息为已读并清空为0
				$.each(submessvm.items, function(index, item) {
					if(type == 'singleChat' && item.id == grounpid) {
						submessvm.items[index].nums = 0;
					}
				});
				localStorageFunc.set(stroagekey, submessvm.items);
			}

			mui.openWindow({
				url: '/html/im-chat.html',
				id: 'im-chat',
				createNew: false,
				extras: {
					'chattype': '0', //chattype类型：0 单聊 ; 1 群聊
					"userid": grounpid, //自定义扩展参数，可以用来处理页面间传值
					"notestype": cname,
					'info': ''
				},
				show: {
					autoShow: true,
					aniShow: 'slide-in-right',
					duration: 300
				},
				waiting: {
					autoShow: true,
					title: '正在加载...'
				}
			});
		} else if(status == '1') { //群聊
			if(submessvm.items.length > 0) { //标记消息为已读并清空为0
				$.each(submessvm.items, function(index, item) {
					if(type == 'groupChat' && item.id == grounpid) {
						submessvm.items[index].nums = 0;
					}
				});

				localStorageFunc.set(stroagekey, submessvm.items);
			}
			mui.openWindow({
				url: '/html/im-chat.html',
				id: 'im-chat',
				createNew: false,
				extras: {
					'chattype': '1', //chattype类型：0 单聊 ; 1 群聊
					"userid": grounpid, //自定义扩展参数，可以用来处理页面间传值
					"notestype": ctitle
				},
				show: {
					autoShow: true,
					aniShow: 'slide-in-right',
					duration: 300
				},
				waiting: {
					autoShow: true,
					title: '正在加载...'
				}
			})

		} else { //	任务消息通知
			jczw.message.read(null, function(result) {
				$("#unreadCount").css("visibility", "hidden");
			});

			mui.openWindow({
				url: '/html/task-notice.html',
				id: 'task-notice',
				createNew: false,
				extras: {
					"notestype": cname, //自定义扩展参数，可以用来处理页面间传值
				},
				show: {
					autoShow: true,
					aniShow: 'slide-in-right',
					duration: 300
				},
				waiting: {
					autoShow: true,
					title: '正在加载...'
				}
			})
		}

	});

	//	下拉刷新
	function pullrefresh() {
		setTimeout(function() {
			mui('#refreshContainer').pullRefresh().endPulldown();
		}, 100);
	}
</script>